<template>
  <div>
    <!-- 搜索框区域 -->
    <div class="xw-block" style="display: flex">
      <el-input
          v-model="pageRequest.q.keywords"
          style="width: 300px"
          placeholder="请输入你想搜索的新闻内容？"
          clearable
          @clear="clearSearch">
      </el-input>
      <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="xw-block" style="display: flex">
      <el-button type="primary" @click="add">新增新闻</el-button>
      <el-popconfirm
          style="margin-left: 5px"
          confirm-button-text="确定"
          cancel-button-text="我再想想"
          icon="el-icon-info"
          icon-color="red"
          title="您确定要删除吗？"
          @confirm="delBatch">
      </el-popconfirm>
    </div>

    <!-- 新闻列表表格 -->
    <el-table
        class="xw-block-table"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 100%">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column
          prop="content"
          label="内容">
        <template slot-scope="scope">
          <div>
            <span v-if="scope.row.isExpanded">{{ scope.row.content }}</span>
            <span v-else>{{ scope.row.content.slice(0, 100) }}...</span>
            <el-link
                v-if="scope.row.content.length > 100"
                type="primary"
                @click="toggleContent(scope.row)">
              {{ scope.row.isExpanded ? '收起' : '展开' }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="edit(scope.row)">编辑</el-button>
          <el-popconfirm
              style="margin-left: 5px"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定要删除吗？"
              @confirm="del(scope.row.id)">
            <el-button slot="reference" size="small">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="xw-block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizeArr"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!-- MyDrawer 编辑抽屉组件 -->
    <MyDrawer ref="MyDrawer" :title="selectRow.id ? '更新新闻' : '新增新闻'" @saveOrUpdate="saveOrUpdate" @close="clearDrawer">
      <el-form class="line" label-position="top" :model="selectRow" :rules="rules" ref="newsForm">
        <el-form-item label="新闻标题" prop="title">
          <el-input placeholder="请输入新闻标题" v-model="selectRow.title"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容" prop="content">
          <el-input
              style="width: 85%"
              type="textarea"
              :rows="13"
              placeholder="请输入新闻内容"
              v-model="selectRow.content">
          </el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input placeholder="请输入创建时间" v-model="selectRow.createTime" disabled></el-input>
        </el-form-item>
      </el-form>
    </MyDrawer>
  </div>
</template>

<script>
import MyDrawer from "@/components/MyDrawer.vue";
import moment from 'moment';

export default {
  data() {
    return {
      delIds: [],
      selectRow: {
        id: null,
        title: '',
        content: '',
        createTime: ''
      },
      rules: {
        title: [
          { required: true, message: '新闻标题不能为空', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '新闻内容不能为空', trigger: 'blur' }
        ]
      },
      pageSizeArr: [10, 20, 30, 40],
      tableData: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        q: {
          keywords: ''
        }
      },
      total: 0
    };
  },
  components: {
    MyDrawer
  },
  mounted() {
    this.load();
  },
  methods: {
    load() {
      this.request.post("/news/all", {
        pageNum: this.pageRequest.pageNum,
        pageSize: this.pageRequest.pageSize,
        keywords: this.pageRequest.q.keywords || ''
      }).then(res => {
        if (res.code === '200') {
          this.tableData = res.data.list.map(item => {
            item.createTime = item.createTime
                ? moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
                : null;
            item.isExpanded = false; // 初始化展开状态
            return item;
          });
          this.total = res.data.total; // 从后端返回的分页总条数
        } else {
          this.messageError("加载数据失败");
        }
      });
    },

    search() {
      this.pageRequest.pageNum = 1; // 搜索时从第一页开始
      this.load();
    },

    clearSearch() {
      this.pageRequest.q.keywords = '';
      this.load();
    },
    edit(row) {
      this.selectRow = { ...row }; // 深拷贝数据，避免修改原数据
      if (this.$refs.newsForm) {
        this.$refs.newsForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open();
    },
    add() {
      this.selectRow = { id: null, title: '', content: '', createTime: '' }; // 初始化数据
      if (this.$refs.newsForm) {
        this.$refs.newsForm.resetFields(); // 重置表单验证状态
      }
      this.$refs.MyDrawer.open();
    },
    del(id) {
      this.request.delete(`/news/${id}`).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功");
          this.load();
        } else {
          this.messageError("删除失败");
        }
      });
    },
    saveOrUpdate() {
      this.$refs.newsForm.validate(valid => {
        if (valid) {
          if (!this.selectRow.id) {
            this.request.post("/news", this.selectRow).then(res => {
              if (res.code === '200') {
                this.messageSuccess("新增成功");
                this.$refs.MyDrawer.close();
                this.load();
              } else {
                this.messageError(res.msg);
              }
            });
          } else {
            this.request.put(`/news/update`, this.selectRow).then(res => {
              if (res.code === '200') {
                this.messageSuccess("修改成功");
                this.$refs.MyDrawer.close();
                this.load();
              } else {
                this.messageError(res.msg);
              }
            });
          }
        } else {
          this.messageError("请检查必填项是否填写完整");
        }
      });
    },
    handleSizeChange(size) {
      this.pageRequest.pageSize = size;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      this.load();
    },
    handleSelectionChange(e) {
      this.delIds = e.map(x => x.id);
    },
    toggleContent(row) {
      row.isExpanded = !row.isExpanded;
    },
    clearDrawer() {
      this.$refs.newsForm.resetFields();
    }
  }
};
</script>

<style scoped>
.xw-block {
  margin-bottom: 10px;
}

.xw-block-table {
  margin-bottom: 20px;
}

.el-button {
  margin-left: 10px;
}

.el-link {
  margin-left: 5px;
  font-size: 12px;
}
</style>
